using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProductionPlans;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Read.Api.Application.Command.ProductionPlans;
using RBAC.Read.Api.Application.Dto;
using RBAC.Read.Api.Utils;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;

namespace RBAC.Read.Api.Controllers
{
    /// <summary>
    /// 生产计划控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductionPlanReadController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ProductionPlanReadController> _logger;

        public ProductionPlanReadController(IMediator mediator, ILogger<ProductionPlanReadController> logger)
        {
            this.mediator = mediator;
            this._logger = logger;
        }

        /// <summary>
        /// 物品表-分页列表
        /// </summary>
        [HttpGet]
        public Task<APIResult<APIPaging<GoodsInfo>>> GetGoodsInfoList([FromQuery] GetGoodsInfoCommands request, CancellationToken cancellationToken)
        {
            return mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 销售表-分页列表（支持：销售单号/客户名称/采购状态）
        /// </summary>
        [HttpGet]
        public Task<APIResult<APIPaging<SalesTable>>> GetSalesTableList([FromQuery] GetSalesTableCommands request, CancellationToken cancellationToken)
        {
            return mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 生产计划-分页列表（字段：序号、计划单号、计划主题、单据日期、物品概述、关联项目、备注）
        /// </summary>
        [HttpGet]
        public Task<APIResult<APIPaging<ProductionPlanListDto>>> GetProductionPlanList([FromQuery] GetProductionPlanCommands request, CancellationToken cancellationToken)
        {
            return mediator.Send(request, cancellationToken);
        }

        /// <summary>
        /// 根据ID获取生产计划（反填）
        /// </summary>
        [HttpGet("{id:long}")]
        public Task<APIResult<ProductionPlan>> GetProductionPlanById([FromRoute] long id, CancellationToken cancellationToken)
        {
            var cmd = new ByIdProductionPlanCommands { ProductionPlanId = id };
            return mediator.Send(cmd, cancellationToken);
        }

        /// <summary>
        /// 导出：生产计划列表（根据筛选条件）
        /// </summary>
        /// <param name="request">筛选与导出参数</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>Excel 文件</returns>
        [HttpGet("ExportProductionPlanList")]
        public async Task<IActionResult> ExportProductionPlanList([FromQuery] ExportProductionPlanCommands request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始导出生产计划列表，筛选条件: {@Request}", request);

                var excelBytes = await mediator.Send(request, cancellationToken);

                if (excelBytes == null || excelBytes.Length == 0)
                {
                    _logger.LogWarning("导出数据为空");
                    return BadRequest("导出数据为空，请检查筛选条件");
                }

                var safeFileName = FileNameHelper.GenerateSafeFileName("ProductionPlan", "xlsx");
                var displayFileName = FileNameHelper.GenerateDisplayFileName("生产计划", "xlsx");
                var contentDisposition = FileNameHelper.GenerateContentDisposition(safeFileName, displayFileName);
                Response.Headers["Content-Disposition"] = contentDisposition;
                Response.Headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
                Response.Headers["Pragma"] = "no-cache";
                Response.Headers["Expires"] = "0";
                Response.Headers["Content-Length"] = excelBytes.Length.ToString();

                const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                _logger.LogInformation("导出生产计划列表完成，文件大小: {Size} bytes", excelBytes.Length);
                return File(excelBytes, contentType, safeFileName);
            }
            catch (OperationCanceledException)
            {
                _logger.LogWarning("导出操作被取消");
                return StatusCode(499, "导出操作被取消");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出生产计划列表失败: {Message}", ex.Message);
                return StatusCode(500, $"导出失败: {ex.Message}");
            }
        }

    }
}
